using OTE.Tasks.Commands.Category;
using SharpArch.Domain.Commands;
using SharpArch.NHibernate.Contracts.Repositories;

namespace OTE.Tasks.CommandHandlers.Category
{
    public class CategoryDeletedHandler : ICommandHandler<CategoryDeletedCommand>
    {
        private readonly INHibernateRepository<Domain.Category> _categoryRepository;

        public CategoryDeletedHandler(INHibernateRepository<Domain.Category> categoryRepository)
        {
            _categoryRepository = categoryRepository;
        }

        public ICommandResult Handle(CategoryDeletedCommand command)
        {
            var uow = _categoryRepository.DbContext;

            var cat = _categoryRepository.Get(command.CategoryId);

            if (cat != null)
            {
                _categoryRepository.Delete(cat);
            }

            uow.CommitChanges();

            var result = cat == null
               ? new CategoryDeletedResult(false)
               : new CategoryDeletedResult(true) { Category = cat };

            return result;
        }
    }
}